<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Spring Boot+WebSocket+广播式</title>
        <link th:href="@{bootstrap/css/bootstrap.min.css}" rel="stylesheet" />
        <link th:href="@{bootstrap/css/bootstrap-theme.min.css}" rel="stylesheet" />
    </head>
    <body onload="disconnect()">
        <noscript>
            <h2 style="color: #f5c6cb"> 你的浏览器不支持webSocket</h2>
        </noscript>
        <div>
            <div>
                <button class="btn" id="connect" onclick="connect();">链接</button>
                <button class="btn" id="disconnect" onclick="disconnect();" disabled="disabled">断开链接</button>
            </div>
            <div id="conversationDiv">
                <label>输入你的名字</label><input type="text" id="name">
                <button id="sendName" onclick="sendName();">发送</button>
                <p id="response"></p>
            </div>
        </div>
        <script th:src="@{socket/sockjs.min.js}"></script>
        <script th:src="@{socket/stomp.min.js}"></script>
        <script th:src="@{bootstrap/js/bootstrap.js}" type="text/javascript"></script>
        <!--<script th:src="@{jquery/jquery-3.3.1.min.js}" type="text/javascript"></script>-->
        <script th:src="@{jquery/jquery-3.3.1.min.js}"></script>
        <script type="text/javascript">
            var stompClient = null;

            function setConnected(connected) {
                document.getElementById('connect').disabled = connected;
                document.getElementById('disconnect').disabled = !connected;
                document.getElementById('conversationDiv').style.visibility = connected ? 'visible' : 'hidden';
                $('#response').html();
            }

            function connect() {
                var socket = new SockJS('/awi/endpoint');
                stompClient = Stomp.over(socket);
                stompClient.connect({},function (frame) {
                    setConnected(true);
                    console.log('connected: ' + frame);
                    stompClient.subscribe('/topic/getResponse',function (response) {
                        showResponse(JSON.parse(response.body).responseMessage);
                    })
                })
            }

            function disconnect() {
                if (stompClient != null){
                    stompClient.disconnect();
                }
                setConnected(false);
                console.log("Disconnected");
            }

            function sendName() {
                var name = $('#name').val();
                stompClient.send("/welcome",{},JSON.stringify({'name':name}));
            }

            function showResponse(message) {
                var response = $('#response');
                response.html(message);
            }

        </script>
    </body>
</html>